//
//  WCDocumentController.m
//  WabbitCode
//
//  Created by William Towe on 1/6/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCDocumentController.h"
#import "WCNewProjectWindowController.h"
#import "WCMacros.h"
#import "WCNewFileWindowController.h"
#import "WCProject.h"
#import "WCNewTargetWindowController.h"
#import "WCTextView.h"
#import "NSArray+WCExtensions.h"
#import "WCBuildTarget.h"
#import "WCAppController.h"


@implementation WCDocumentController
#pragma mark *** Subclass Overrides ***
#pragma mark Validation
- (BOOL)validateUserInterfaceItem:(id < NSValidatedUserInterfaceItem >)item {
	SEL action = [item action];
	
	if (action == @selector(newFileAction:)) {
		if (![self currentProject])
			return NO;
		else if ([[[self currentProject] projectWindow] attachedSheet])
			return NO;
	}
	else if (action == @selector(newTargetAction:)) {
		if (![self currentProject])
			return NO;
		else if ([[[self currentProject] projectWindow] attachedSheet])
			return NO;
	}
	return YES;
}
#pragma mark *** Public Methods ***
- (BOOL)openMostRecentProject; {
	for (NSURL *url in [self recentDocumentURLs]) {
		if ([[self typeForContentsOfURL:url error:NULL] isEqualToString:kWCProjectUTI]) {
			if ([self openDocumentWithContentsOfURL:url display:YES error:NULL])
				return YES;
		}
	}
	return NO;
}
#pragma mark Accessors
@dynamic currentProject;
- (WCProject *)currentProject {
	id document = [self currentDocument];
	if ([document isKindOfClass:[WCProject class]])
		return document;
	return nil;
}
@dynamic currentTextView;
- (WCTextView *)currentTextView {
	WCProject *project = [self currentProject];
	if (project)
		return [project currentTextView];
	
	NSWindow *window = [NSApp mainWindow];
	if ([[window firstResponder] isKindOfClass:[WCTextView class]])
		return (WCTextView *)[window firstResponder];
	return nil;
}

@dynamic allProjects;
- (NSArray *)allProjects {
	NSMutableArray *projects = [NSMutableArray array];
	
	for (id document in [self documents]) {
		if ([document isKindOfClass:[WCProject class]])
			[projects addObject:document];
	}
	return [[projects copy] autorelease];
}
#pragma mark IBActions
- (IBAction)newFileAction:(id)sender; {
	[[WCNewFileWindowController sharedInstance] presentNewFileWindow];
}
- (IBAction)newEmptyFileAction:(id)sender; {
	[[WCDocumentController sharedDocumentController] newDocument:nil];
}
- (IBAction)newProjectAction:(id)sender; {
	[[WCNewProjectWindowController sharedInstance] presentNewProjectWindow];
}
- (IBAction)newTargetAction:(id)sender; {
	[[WCNewTargetWindowController sharedInstance] presentNewTargetWindow];
}

- (IBAction)openMostRecentProjectAction:(id)sender; {
	[self openMostRecentProject];
}
@end
